package com.hao.controller;

import com.hao.mapper.UserMapper;
import com.hao.pojo.User;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;

import org.springframework.web.bind.annotation.PostMapping;


import java.util.List;

@Controller
public class LoginController {
    @Autowired
    UserMapper usermapper;
    @GetMapping("/out")
    public String welcome(){
        return "login";
    }
    @GetMapping({"/","index"})
    public String index(){
        return "index";
    }
    @PostMapping("/login")
    public String login(User user, Model model){
        //获取当前用户
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(user.getUsername(), user.getPassword());
        try {
            subject.login(token);
            return "index";
        } catch (UnknownAccountException e) {
            model.addAttribute("msg","用户名错误");
            return "login";
        } catch (IncorrectCredentialsException e){
            model.addAttribute("msg","密码错误");
            return "login";
        }

    }
    @GetMapping("/register")
    public String register(){
        return "register";
    }
    @PostMapping("/register")
    public String zc(User user){
        System.out.println(user);
        Integer add = usermapper.add(user);
        if(add!=0){
            System.out.println("添加成功");
            return "login";
        }else{
            return null;
        }
    }
    @GetMapping("/delete/id")
    public String delete(Integer id){
        Integer delete = usermapper.delete(id);
        if(delete!=0){
            return "redirect:/ml";
        }
        return null;
    }

}
